package com.hiwhitley.easy.day23;

/**
 * Created by hiwhitley on 2016/10/15.
 */
public class StringToInteger_8 {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        int i = 0, len = str.length();
        int num = 0, sign = 1, bound = Integer.MAX_VALUE / 10;

        // 1. Remove whitespace
        while (i < len && str.charAt(i) == ' ') i++;

        // 2. Handle signs
        if (i < len && (str.charAt(i) == '+' || str.charAt(i) == '-')) {
            sign = str.charAt(i++) == '-' ? -1 : 1;
        }

        // 3. Convert number
        while (i < len && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            int digit = str.charAt(i++) - '0';
            boolean overlow = (num == bound && digit >= 8) || num > bound;
            if (overlow) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            num = num * 10 + digit;
        }

        return sign * num;
    }

    public static void main(String[] args) {
        StringToInteger_8 main = new StringToInteger_8();
        System.out.println(main.myAtoi("2147483648"));
    }
}
